﻿using System;
using System.IO;
using System.Text;

namespace Inaction.Util
{
    public static class FileHelper
    {
        private static object LockFlag = 0;
        public static void WriteText(string filePath, string fileContent, FileMode? fileMode = null)
        {
            FileInfo fileInfo = new FileInfo(filePath);
            if (!Directory.Exists(fileInfo.DirectoryName))
            {
                Directory.CreateDirectory(fileInfo.DirectoryName);
            }
            TextWriter tw = null;
            lock (LockFlag)
            {
                try
                {

                    if (fileMode == null)
                    {
                        if (fileInfo.Exists)
                        {
                            tw = new StreamWriter(fileInfo.Open(FileMode.Append, FileAccess.Write), Encoding.UTF8);
                        }
                        else
                        {
                            tw = new StreamWriter(fileInfo.Open(FileMode.Create, FileAccess.Write), Encoding.UTF8);
                        }
                    }
                    else
                    {
                        tw = new StreamWriter(fileInfo.Open(fileMode.Value, FileAccess.Write), Encoding.UTF8);
                    }
                    if (!fileContent.EndsWith(Environment.NewLine))
                    {
                        fileContent += Environment.NewLine;
                    }
                    tw.Write(fileContent);
                    tw.Flush();
                }
                catch (Exception) { throw; }
                finally
                {
                    if (tw != null)
                    {
                        tw.Close();
                    }
                }
            }
        }
        public static string ReadFile(string filePath)
        {
            using (StreamReader sr = File.OpenText(filePath))
            {
                try
                {
                    var result = sr.ReadToEnd();
                    return result;
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
    }
}
